<%@ page language="java" contentType="text/html; charset=UTF-8"
		 pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%@ page import="cn.estore.util.DBConnection" %>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>用户登录验证</title>
</head>
<body>
<%
	request.setCharacterEncoding("UTF-8");
	// 获取用户输入的用户名、密码和是否记住登录状态的选项
	String username = request.getParameter("username");
	String pwd = request.getParameter("pwd");
	String jizhu = request.getParameter("jizhu");

	Connection conn = null;
	PreparedStatement stmt = null;
	ResultSet rs = null;
	try {
		// 获取数据库连接
		DBConnection jdbc = new DBConnection();
		conn = jdbc.getConnection();
		// 使用PreparedStatement构建查询语句，防止SQL注入
		String sql = "select * from user where username =? and pwd =?";
		stmt = conn.prepareStatement(sql);
		stmt.setString(1, username);
		stmt.setString(2, pwd);
		rs = stmt.executeQuery();

		if (rs.next()) {
			if ("yes".equals(jizhu)) {
				// 如果用户选择记住登录，创建并设置Cookie
				Cookie c = new Cookie("username", username);
				Cookie d = new Cookie("user_id", String.valueOf(rs.getInt("id")));
				System.out.println(rs.getInt("id"));
				c.setMaxAge(24 * 60 * 60);
				d.setMaxAge(24 * 60 * 60);
				response.addCookie(c);
				response.addCookie(d);
			}
			// 登录成功，重定向到登录成功页面
			response.sendRedirect("loginsuccess.jsp");
		} else {
			// 登录失败，输出提示信息给用户
			out.print("用户名或密码错误，登录失败！");
		}
	} catch (SQLException e) {
		e.printStackTrace();
		out.print("数据库操作出现异常，请稍后再试！");
	} finally {
		// 关闭资源，释放连接等，避免资源泄漏
		try {
			if (rs!= null) {
				rs.close();
			}
			if (stmt!= null) {
				stmt.close();
			}
			if (conn!= null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
%>
</body>
</html>
